package tests;

import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import junit.framework.TestCase;
import lz77.Buffer;

public class BufferTest extends TestCase {

	Buffer b;
	String data;

	protected void setUp() throws Exception {
		super.setUp();
		data = "abcdefghijklabcdefghijkl";
		InputStream in = new ByteArrayInputStream(data.getBytes("UTF-8"));
		b = new Buffer(in, (char) 12);
	}

	public void testNext() throws IOException {
		assertEquals(b.get(b.bufferEnd), (byte) 'a');
		try {
			b.next();
		} catch (IOException e) {
			fail();
		}
		assertEquals(b.get(b.bufferEnd), (byte) 'b');
		
		for (int i = 0; i < data.length() - 2; i++) {
			try {
				b.next();
			} catch (IOException e) {
				fail();
			}
		}

		boolean thrown = false;
		// tiedoston pitäisi loppua
		try {
			b.next();
		} catch (EOFException e) {
			thrown = true;
		}

		assertTrue(thrown);
	}

	public void testKmp_find() throws IOException {
		byte[] needle = "cde".getBytes("UTF-8");
		for (int i = 0; i < 6; i++) {
			b.next();
		}
		char[] result = b.kmp_find(needle);
		assertEquals(result[1], 3);
		assertEquals(result[0], 2);

		needle = "abcdabc".getBytes("UTF-8");
		result = b.kmp_find(needle);
		assertEquals(result[1], 4);
		assertEquals(result[0], 0);

		needle = "nomnomnokasd".getBytes("UTF-8");
		result = b.kmp_find(needle);

		assertEquals(result[1], 0);
	}
	
	public void testGetNextString() throws UnsupportedEncodingException{
		byte[] dataBytes = data.getBytes("UTF-8");
		byte[] result = b.getNextString();
		for (int i =0; i < result.length; i++){
			assertEquals(dataBytes[i], result[i]);
		}
	}

}
